import { useEffect, useRef, useState } from 'react'
import { Tag, Input, Tooltip } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import styles from './index.less'

/**
 * 可编辑的属性数组
 */
const EditableAttrs = (props) => {
  const { value, onChange }=props
  const [inputVisible, setInputVisible] = useState(false)
  const [inputValue, setInputValue] = useState('')

  const input = useRef(null)

  useEffect(() => {
    if (input.current && inputVisible) {
      input.current.focus()
    }
  }, [inputVisible])

  const showInput = () => {
    setInputVisible(true)
  }

  const handleInputChange = e => {
    setInputValue(e.target.value)
  }

  const handleInputConfirm = () => {
    let newTags = value
    if (inputValue && value.indexOf(inputValue) === -1) {
      newTags = [...value, inputValue];
    }
    onChange(newTags)
    setInputValue('')
    setInputVisible(false)
  }

  return (
    <>
      {value.map((tag, index) => {
        const isLongTag = tag.length > 20;

        const tagElem = (
          <Tag
            className={styles.editTag}
            key={tag}
          >
            <span>
              {isLongTag ? `${tag.slice(0, 20)}...` : tag}
            </span>
          </Tag>
        );
        return isLongTag ? (
          <Tooltip title={tag} key={tag}>
            {tagElem}
          </Tooltip>
        ) : (
          tagElem
        );
      })}
      {inputVisible && (
        <Input
          ref={input}
          type="text"
          size="small"
          className={styles.tagInput}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      )}
      {!inputVisible && (
        <Tag className={styles.tagPlus} onClick={showInput}>
          <PlusOutlined /> 添加属性
        </Tag>
      )}
    </>
  );

}

export default EditableAttrs
